package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.enums.eUnionPosition;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Protocol.S_UNION_CHANGE_RANK_GRADE_JOIN_LIMIT, desc = "修改实力档位加入限制")
public class ChangeRankGradeJoinLimitCmd extends AbstractCommand {

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		UnionProto.ChangeUnionRankGradeJoinLimitReqMsg reqMsg = UnionProto.ChangeUnionRankGradeJoinLimitReqMsg.parseFrom(packet.getBytes());
		String unionUid = player.getUserInfo().getUnionUid();
		if (StringUtils.isNullOrEmpty(unionUid)) {
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
		if (null == unionInfo) {
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		int crossServerCount = CrossUnionServerGroupMgr.getGroupServerCountByServerId(unionInfo.getServerId());
		if(crossServerCount < GameConfig.UNION_PLAYER_OPEN_COND_AREA_NUM){
			ret = GameErrorCode.E_UNION_CROSS_GROUP_LIMIT;
			return;
		}
		CrossUnionMember member = CrossUnionMgr.getUnionMember(unionUid, player.getUserId());
		if(member == null || StringUtils.isNullOrEmpty(member.getUnionUid())){
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		if (member.getPosition() == eUnionPosition.Master.getValue()
				|| member.getPosition() == eUnionPosition.DeputyMaster.getValue()) {
			player.sendPacket(Protocol.C_UNION_CROSS_CHANGE_RANK_GRADE_JOIN_LIMIT, reqMsg.toBuilder());
		} else {
			ret = GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		if(ret != 0) {
			UnionProto.ChangeUnionRankGradeJoinLimitRespMsg.Builder respMsg = UnionProto.ChangeUnionRankGradeJoinLimitRespMsg.newBuilder();
			respMsg.setRet(ret);
			player.sendPacket(Protocol.U_UNION_CHANGE_RANK_GRADE_JOIN_LIMIT, respMsg);
		}
	}

}
